package com.zdb.n1.controller;

import com.zdb.n1.payload.request.UpdateUserRequest;
import com.zdb.n1.payload.request.AdminUpdateUserRequest;
import com.zdb.n1.payload.request.AdminCreateUserRequest;
import com.zdb.n1.payload.response.MessageResponse;
import com.zdb.n1.payload.response.UserResponse;
import com.zdb.n1.service.UserService;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/users")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/profile")
    public ResponseEntity<UserResponse> getCurrentUserProfile() {
        return ResponseEntity.ok(UserResponse.fromEntity(userService.getCurrentUser()));
    }

    @GetMapping("/{userId}")
    public ResponseEntity<UserResponse> getUserProfile(@PathVariable Long userId) {
        return ResponseEntity.ok(userService.getUserProfile(userId));
    }

    @PutMapping("/profile")
    public ResponseEntity<UserResponse> updateUserProfile(@Valid @RequestBody UpdateUserRequest updateUserRequest) {
        return ResponseEntity.ok(userService.updateUserProfile(updateUserRequest));
    }

    @PutMapping("/change-password")
    public ResponseEntity<MessageResponse> changePassword(
            @RequestParam String currentPassword,
            @RequestParam String newPassword) {
        return ResponseEntity.ok(userService.changePassword(currentPassword, newPassword));
    }

    @GetMapping
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<List<UserResponse>> getAllUsers() {
        return ResponseEntity.ok(userService.getAllUsers());
    }

    @DeleteMapping("/{userId}")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<MessageResponse> deleteUser(@PathVariable Long userId) {
        return ResponseEntity.ok(userService.deleteUser(userId));
    }

    @PutMapping("/admin/{userId}")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<UserResponse> adminUpdateUser(
            @PathVariable Long userId,
            @Valid @RequestBody AdminUpdateUserRequest adminUpdateUserRequest) {
        return ResponseEntity.ok(userService.adminUpdateUser(userId, adminUpdateUserRequest));
    }

    @PostMapping("/admin/create")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<UserResponse> adminCreateUser(@Valid @RequestBody AdminCreateUserRequest request) {
        return ResponseEntity.ok(userService.adminCreateUser(request));
    }
} 